<template>
<div class="shareList">
  <search-block type="flex">
    <template slot="button">
      <el-button type="primary" @click="search(true)">查询</el-button>
      <el-button type="primary" @click="addShare">添加模板</el-button>
    </template>
    <el-form inline :model="model" @submit.native.prevent>
      <el-form-item label="标题:">
        <el-input v-model="model.title" clearable></el-input>
      </el-form-item>
    </el-form>
  </search-block>
  <y-table
    ref="table"
    border
    pagination
    :getDataWay="getDataWay"
    :columns="columns">
    <el-table-column slot="icon" label="当前图片" align="center" header-align="center" width="120">
      <template v-slot="{row}">
        <img v-if="row.list && row.list.length" style="max-width: 100%" :src="generateMediaUrl({fileOpenUrl: row.list[0].icon})"/>
      </template>
    </el-table-column>
    <el-table-column slot="y-oper" label="操作" align="center" header-align="center" width="150">
      <template v-slot="{row}">
        <div class="table-buttons">
          <el-button type="primary" size="mini" @click="editShare(row)">编辑</el-button>
          <el-popconfirm
              title="是否确认删除该模板？"
              @confirm="delShare(row)">
            <el-button slot="reference" type="danger" size="mini">删除</el-button>
          </el-popconfirm>
        </div>
      </template>
    </el-table-column>
  </y-table>
  <y-form
    v-model="forms.formModel"
    :visible.sync="forms.showForm"
    :title="forms.formTypeTitle[forms.formsType]"
    destroy-on-close
    width="900px"
    force-inner-scroll
    :form-attrs="forms.formAttrs"
    :columns="formColumns"
    @ensure="ensureModel">
    <template slot="list">
      <draggable
        v-model="forms.formModel.list"
        v-if="forms.formModel && Array.isArray(forms.formModel.list)">
        <share-photos-item
          v-for="(item, index) in forms.formModel.list"
          :key="item.attachmentId || index"
          :model="item"
          :business-id="forms.formModel.businessId"
          @add="addPhoto"
          @delete="delPhoto(index)"></share-photos-item>
      </draggable>
    </template>
  </y-form>
</div>
</template>

<script>
import draggable from 'vuedraggable'
import SharePhotosItem from "@/views/applet/sharePhotosItem";
export default {
  name: "shareList",
  components: {draggable, SharePhotosItem},
  inject: ['generateMediaUrl', 'getDictNameSync'],
  computed:{
    getDataWay(){
      return{
        dataType: 'url',
        data: this.$api.applet.sharePage,
        param: this.model
      }
    },
    formColumns() {
      return [
        {
          label: "标题",
          prop: "title",
          comp: {
            compType: 'input',
            attrs:{
              maxlength: 30,
              showWordLimit: true
            }
          }
        },
        {
          label: "业务模块",
          prop: "businessId",
          comp: {
            compType: 'YCodeSelect',
            attrs: {
              dict: 'SHARE_MODULE'
            }
          }
        },
        {
          label: '图片',
          prop: 'list',
          class: 'is-required',
          template: true
        }
      ]
    }
  },
  data(){
    return{
      model:{
        title: ''
      },
      columns:[
        {
          label: '标题',
          prop: 'title'
        },
        {
          label: "指标类型",
          prop: "businessId",
          formatter: (function(row){
            return this.getDictNameSync(row.businessId, 'SHARE_MODULE');
          }).bind(this)
        },
        {
          prop: 'icon',
          template: true
        }
      ],
      forms:{
        formsType: '',
        formTypeTitle: {
          'ADD': '添加模板',
          'EDIT': '编辑模板'
        },
        formModel:{
          title: '',
          list: [],
          businessId: ''
        },
        currentForm: null,
        showForm: false,
        formAttrs:{
          labelWidth: '100px',
          rules: {
            title: [{required: true, message: "请输入标题", trigger: "blur"}],
            businessId: [{required: true, message: "请选择业务模块", trigger: "change"}],
            list: [
              {
                validator: (rule, value, callback) => {
                  if(!this.forms.formModel.list.length){
                    callback(new Error('请上传图片'));
                  }
                  callback();
                },
                trigger: 'change'
              }
            ]
          }
        }
      }
    }
  },
  methods:{
    resetForm(){
      Object.keys(this.forms.formModel).map(key => {
        if(key === 'list'){
          this.forms.formModel[key] = this.forms.currentForm ? this.forms.currentForm[key].map(obj => ({...obj})) : [];
        }
        else this.forms.formModel[key] = this.forms.currentForm ? this.forms.currentForm[key] : '';
      })
      //只能有一个图片,加一句条件判断
      if(!this.forms.formModel.list.length)
        this.forms.formModel.list.push({
          attachmentId: "",
          uri: "",
          icon: "",
        })
    },
    search(jumpToFirst){
      this.$refs['table'].loadData(this.model, jumpToFirst);
    },
    addShare(){
      this.forms.formsType = 'ADD';
      this.forms.currentForm = null;
      this.resetForm();
      this.forms.showForm = true;
    },
    editShare(row){
      this.forms.formsType = 'EDIT';
      this.forms.currentForm = row;
      this.resetForm();
      this.forms.showForm = true;
    },
    delShare(row){
      this.$yAxios({
        url: this.$api.applet.removeShare,
        data:{
          ids: row.list.map(item => item.id)
        }
      }, info => {
        this.$message({
          type: 'success',
          message: '删除成功'
        });
        this.search();
      })
    },
    ensureModel(form){
      let newForm;
      if(this.forms.formsType === 'EDIT'){
        newForm = Object.assign({}, this.forms.currentForm, form);
      }else{
        newForm = Object.assign({}, form);
      }
      if(Array.isArray(newForm.list)){
        newForm.list = newForm.list.filter(item => !!item.icon);
        newForm.list.map((item, index) => {
          item.sort = index
        });
      }
      this.$yAxios({
        url: this.$api.applet.saveShare,
        data: newForm
      }, info => {
        this.$message({
          type: 'success',
          message: '保存成功'
        });
        this.search(this.forms.formsType === 'ADD');
      })
    },
    addPhoto(){
      /*只能有一个图片*/
      /*this.forms.formModel.list.push({
        attachmentId: "",
        uri: "",
        icon: "",
      });*/
    },
    delPhoto(index){
      /*只能有一个图片*/
      /*this.$delete(this.forms.formModel.list, index);*/
      let obj = this.forms.formModel.list[index];
      Object.keys(obj).map(key => {
        obj[key] = '';
      })
    }
  }
}
</script>

<style scoped>

</style>
